上一篇講到執行緒的同步,
今天要跟大家分享的是執行緒的等待與喚醒,
Object物件中提供wait() notify() notify All()方法,
可以讓執行緒間相互設定等待和喚醒。
Wait():讓指定的執行緒進入Wait pool成為等待狀態,每個物件都有自己專有的Wait pool。
notify():喚醒一個在Wait pool等待的執行緒,被喚醒的執行緒由JVM決定。
notifyAll():喚醒所有在Wait pool等待的執行緒,先後順序由JVM決定。
class Ball {
private boolean isThrow = false;
public synchronized void throwF(int tNo) {
while (isThrow) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("丟出第 " + tNo + " 顆球");
isThrow = true;
notify();
}
public synchronized void accessF(int aNo) {
while (!isThrow) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("接到第 " + aNo + " 顆球");
isThrow = false;
notify();
}
}
class ThrowFrisbee implements Runnable {
Ball frisbee;
ThrowFrisbee(Ball frisbee) {
this.frisbee = frisbee;
}
public void run() {
for (int i = 1; i <= 5; i++) {
frisbee.throwF(i);
}
}
}
class AccessFrisbee implements Runnable {
Ball frisbee;
AccessFrisbee(Ball frisbee) {
this.frisbee = frisbee;
}
public void run() {
for (int i = 1; i <= 5; i++) {
frisbee.accessF(i);
}
}
}
public class WaitNotify {
public static void main(String[] atgs) {
Ball frisbee = new Ball();
Thread master = new Thread(new ThrowFrisbee(frisbee));
Thread dog = new Thread(new AccessFrisbee(frisbee));
master.start();
dog.start();
}
}